package cn.ncupyh.dao;

import cn.ncupyh.entity.User;
import cn.ncupyh.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//Dao层也叫持久层
public class UserDao {

    //    1.添加User
    public boolean addUser(User user) throws SQLException {
        boolean flag = false;
        PreparedStatement pstmt = null;
        Connection conn = JDBCUtils.getConn();
        String sql = "insert into user(uname,upassword) values(?,?)";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUname());
            pstmt.setString(2, user.getUpassword());
            int num = pstmt.executeUpdate();
            if(num > 0){
                flag = true;
            }
        } catch (SQLException e) {
//            throwables.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            JDBCUtils.release(conn,pstmt);
        }
        return flag;
    }
//    2.更新User
    public boolean updateUser(User user) throws SQLException {
        boolean flag = false;
        Connection conn = JDBCUtils.getConn();
        PreparedStatement pstmt = null;
//        Connection conn = JDBCUtils.getConn();
        String sql = "update user set upassword = ? where uname = 'lisi'";
        try {
            pstmt = conn.prepareStatement(sql);
//            pstmt.setString(1,user.getUname());
            pstmt.setString(1,user.getUpassword());
            int num = pstmt.executeUpdate();
            if(num > 0){
                flag = true;
            }
        } catch (SQLException e) {
//            throwables.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            JDBCUtils.release(conn,pstmt);
        }
        return flag;
    }

//    3.删除User
public boolean deleteUser(User user) throws SQLException {
    boolean flag = false;
    Connection conn = JDBCUtils.getConn();
    PreparedStatement pstmt = null;
//        Connection conn = JDBCUtils.getConn();
    String sql = "delete from user where uname = ?";
    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,user.getUname());
//        pstmt.setString(1,user.getUname());
        int num = pstmt.executeUpdate();
        if(num > 0){
            flag = true;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }finally {
        JDBCUtils.release(conn,pstmt);
    }
    return flag;
}
//    4.查询所有

//    5.查询单个

}
